package UDP网络计算器;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class CalClient {
    private DatagramSocket socket=null;
    private String serverIp;
    private int serverPort;

    public CalClient(String serverIp,int serverPort) throws SocketException {
        this.serverIp=serverIp;
        this.serverPort=serverPort;
        this.socket=new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner scanner=new Scanner(System.in);
        while (true) {
            //1.让用户进行输入
            System.out.println("请输入操作数 num1: ,-1表示退出");
            int num1 = scanner.nextInt();
            if (num1==-1) {
                System.out.println("程序退出");
                return;
            }
            System.out.println("请输入操作数 num2: ");
            int num2 = scanner.nextInt();
            System.out.println("请输入运算符: ");
            String operator = scanner.next();

            //2.根据用户输入构造请求
            String request = num1+";"+num2+";"+operator;
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);

            //3.向服务器发送请求
            socket.send(requestPacket);

            //4.尝试读取来自服务器的响应
            DatagramPacket responsePacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);

            //显示响应结果
            String response=new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println("计算结果为 "+ response);
        }
    }

    public static void main(String[] args) throws IOException {
        CalClient client=new CalClient("127.0.0.1",9096);
        client.start();
    }
}
